package com.fjwt.gz.mgr.service.qrshell;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* 仅二维码图片生成器
*
* @author wg
* @site https://pt.jdyd.xyz/
* @date 2022/1/17 17:36
*/
@Data
@Service
public class ShellQRGenerator extends AbstractGenerator{

    /** 生成二维码图片的 buffer缓冲值 **/
    @Override
    public BufferedImage genQrImgBuffer(String configModelStr, String qrUrlContent, Long qrcId, boolean isViewFlag) throws IOException, WriterException {

        String qrId = "";
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrUrlContent, BarcodeFormat.QR_CODE, 570, 570, hints);// 生成矩阵
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        Graphics2D graphic = bufferedImage.createGraphics();
        graphic.setColor(Color.black);//黑色
        Font qrIdFont = new Font("宋体", Font.BOLD, ( bufferedImage.getWidth() / 200 ) * 12);
        FontMetrics metrics = graphic.getFontMetrics(qrIdFont);
        int x = (bufferedImage.getWidth() - metrics.stringWidth(qrId)) / 2;

        graphic.setFont(qrIdFont); //字体、字型、字号
        graphic.drawString(qrId , x, bufferedImage.getHeight() - ( bufferedImage.getWidth() / 200 ) * 10); //画文字
        graphic.drawRenderedImage(bufferedImage, null);
        graphic.dispose();
        return bufferedImage;
    }

}
